﻿using Newtonsoft.Json;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using XYX.Print.Impl;
using XYX.Print.Models;
using XYX.Print.Utils;
using XYX.Print.Utils.GridReport;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TaskBand;

namespace XYX.Print.Client.PrintUI
{
    /// <summary>
    /// 扫描
    /// </summary>
    public partial class ScanBarCodeForm : UIForm
    {
        /// <summary>
        /// 打印报表
        /// </summary>
        private GridReport gridReport = new GridReport();
        /// <summary>
        /// 组码
        /// </summary>

        private string groupCode = string.Empty;
        /// <summary>
        /// 扫描集合
        /// </summary>

        private List<ScanBarCodeRecord> scanBarCodeRecords = new List<ScanBarCodeRecord>();

        /// <summary>
        /// 绑定表格
        /// </summary>
        private DataTable dataTable = new DataTable();

        /// <summary>
        /// 扫码配置
        /// </summary>

        private ScanBarCodeConfigJson scanBarCodeConfigJson;

        /// <summary>
        /// 多个条码为一组
        /// </summary>
        private int groupCount => scanBarCodeConfigJson?.GroupCount ?? 3;

        /// <summary>
        /// 条码长度
        /// </summary>
        private int requrieLength => scanBarCodeConfigJson?.GroupCount ?? 0;
        /// <summary>
        /// 打印模板
        /// </summary>
        private string templateFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "BarCodeTemplate", "barcode.grf");
        /// <summary>
        /// 扫描成功个数
        /// </summary>

        private int successCount = 0;
        /// <summary>
        /// 扫描失败
        /// </summary>
        private int failureCount = 0;
        /// <summary>
        /// 构造
        /// </summary>
        public ScanBarCodeForm()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ScanBarCodeForm_Load(object sender, EventArgs e)
        {
            if (!DesignMode)
            {
                this.lbScanCountMessage.Text = string.Empty;
            }
            //颜色
            txtMessage.SelectionColor = Color.FromArgb(64, 165, 252);
            ClearBarCodeText();
            InitGridData();
            SetScanBarCodeConfigJson();
        }



        /// <summary>
        /// 获取配置
        /// </summary>
        /// <returns></returns>
        private void SetScanBarCodeConfigJson()
        {
            string code = "ScanBarCode";
            scanBarCodeConfigJson = GetScanBarCodeConfigJson(code);
            if (scanBarCodeConfigJson == null)
            {
                scanBarCodeConfigJson = new ScanBarCodeConfigJson()
                {
                    GroupCount = 10,
                    Prefix = string.Empty,
                    RequrieLength = 0
                };
                new ScanBarCodeConfigImpl().Insert(new List<ScanBarCodeConfig>()
                {
                    new ScanBarCodeConfig()
                    {
                        Code=code,
                        CreateDateTime=DateTime.Now,
                        CreateUserId=UserSession.UserId,
                        CreateUserName=UserSession.UserName,
                        Ip=string.Empty,
                        IsDeleted=false,
                        Json=JsonConvert.SerializeObject(scanBarCodeConfigJson),
                    }
                });
            }

        }

        /// <summary>
        /// 获取配置
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private ScanBarCodeConfigJson GetScanBarCodeConfigJson(string code)
        {
            ScanBarCodeConfigImpl numberConfigImpl = new ScanBarCodeConfigImpl();
            ScanBarCodeConfig cfg = numberConfigImpl.QueryFirst(code);
            if (cfg != null && !string.IsNullOrEmpty(cfg.Json))
            {
                return JsonConvert.DeserializeObject<ScanBarCodeConfigJson>(cfg.Json);
            }
            return null;

        }






        /// <summary>
        /// 清空
        /// </summary>
        private void ClearBarCodeText()
        {
            txtBarCode.Text = string.Empty;
            txtBarCode.Focus();
        }
        /// <summary>
        /// 扫描回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtBarCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                try
                {

                    CreateGruopCode();
                    string barCode = this.txtBarCode.Text;
                    if (string.IsNullOrEmpty(barCode))
                    {
                        ShowMessage("条码不能为空", ScanResult.Ng);
                        return;
                    }
                    if (requrieLength > 0 && barCode.Length < requrieLength)
                    {
                        ShowMessage($"条码长度应该是【{requrieLength}】", ScanResult.Ng);
                        ClearBarCodeText();
                        SetlScanCount(false);
                        return;
                    }
                    if (scanBarCodeRecords.Any(it => it.BarCode == barCode))
                    {
                        ShowMessage($"此组条码【{barCode}】已存在", ScanResult.Ng);
                        ClearBarCodeText();
                        SetlScanCount(false);
                        return;
                    }

                    ScanBarCodeRecordImpl scanBarCodeRecordImpl = new ScanBarCodeRecordImpl();
                    scanBarCodeRecordImpl.CheckIsExists(barCode);

                    ScanBarCodeRecord scanBarCodeRecord = CreateScanBarCodeRecord(barCode);
                    //添加到集合
                    scanBarCodeRecords.Add(scanBarCodeRecord);
                    SetlScanCount(true);

                    //绑到定表格
                    InsertGrid(scanBarCodeRecord);

                    //添加到数据库
                    InsertscanBarCodeRecord(barCode);
                    //提示
                    ShowMessage($"条码【{barCode}】检测通过", ScanResult.Pass);
                }
                catch (Exception ex)
                {
                    ShowMessage(ex.Message, ScanResult.Ng);
                    SetlScanCount(false);
                }
                finally
                {
                 
                    ClearBarCodeText();
                }
            }
        }

        /// <summary>
        /// 插入扫描记录表
        /// </summary>
        /// <param name="barCode"></param>
        private void InsertscanBarCodeRecord(string barCode)
        {
            if (scanBarCodeRecords.Count == groupCount)
            {
                ScanBarCodeRecordImpl scanBarCodeRecordImpl = new ScanBarCodeRecordImpl();
                scanBarCodeRecordImpl.Insert(scanBarCodeRecords);
                InsertPrintRecord(barCode);
                scanBarCodeRecords.Clear();

                ShowMessage("添加数据成功", ScanResult.Pass);

                //打印
                var paramaters = CreatePrintParamater(barCode);
                Print(paramaters);
                ShowMessage("打印条码成功", ScanResult.Pass);

                ClearGrid();
            }

        }
        /// <summary>
        /// 插入打印记录
        /// </summary>
        /// <param name="barCode"></param>
        /// <returns></returns>
        private bool InsertPrintRecord(string barCode)
        {
            ScanBarCodePrintRecordImpl scanBarCodePrintRecordImpl = new ScanBarCodePrintRecordImpl();
            scanBarCodePrintRecordImpl.Insert(new List<ScanBarCodePrintRecord>()
            {
                new ScanBarCodePrintRecord()
                {
                    BarCode= barCode,
                    CreateDateTime=DateTime.Now,
                    CreateUserId=UserSession.UserId,
                    CreateUserName=UserSession.UserName,
                    GroupCode=groupCode,
                    IsDeleted=false,
                    PrintBarCodeTemplateName=templateFile,
                    PrintDateTime=DateTime.Now,
                    PrintTimes=1,
                    Remark=string.Empty,
                    Sort=1
                }
            });
            return true;
        }
        /// <summary>
        /// 设置扫码数量
        /// </summary>
        private void SetlScanCount(bool isSuccess = true)
        {
            if (isSuccess)
            {
                successCount += 1;
            }
            else
            {
                failureCount += 1;
            }
            int total = successCount + failureCount;
            lbScanCountMessage.Text = $"当前扫码总数【{total}】,成功【{successCount}】,失败【{failureCount}】";

        }


        /// <summary>
        /// 创建参数
        /// </summary>
        /// <param name="barCode"></param>
        /// <returns></returns>
        private Dictionary<string, string> CreatePrintParamater(string barCode)
        {
            var dic = new Dictionary<string, string>() { };
            dic.Add("BarCode", barCode);
            return dic;
        }

        /// <summary>
        /// 创建分组
        /// </summary>
        private void CreateGruopCode()
        {
            if (scanBarCodeRecords.Count == 0)
            {
                this.groupCode = System.Guid.NewGuid().ToString("N");
            }
        }


        /// <summary>
        /// 初始化表格
        /// </summary>
        private DataTable InitGridData()
        {
            dataTable = new DataTable();
            dataTable.Columns.Add(nameof(ScanBarCodeData.Index), typeof(int));
            dataTable.Columns.Add(nameof(ScanBarCodeData.BarCode), typeof(string));
            dataTable.Columns.Add(nameof(ScanBarCodeData.GroupCode), typeof(string));
            dataTable.Columns.Add(nameof(ScanBarCodeData.Sort), typeof(int));
            dataTable.Columns.Add(nameof(ScanBarCodeData.CreateDateTime), typeof(DateTime)); ;
            dgvScanBarCode.DataSource = dataTable;
            return dataTable;
        }
        /// <summary>
        /// 绑定到表格
        /// </summary>
        /// <param name="scanBarCodeModel"></param>
        private void InsertGrid(ScanBarCodeRecord scanBarCodeRecord)
        {

            var barCodeCount = dataTable.AsEnumerable().Count(it => it[nameof(ScanBarCodeData.GroupCode)].ToString() == scanBarCodeRecord.GroupCode);
            barCodeCount += 1;
            int index = dataTable.Rows.Count + 1;
            DataRow dr = dataTable.NewRow();
            dr[nameof(ScanBarCodeData.Index)] = index;
            dr[nameof(ScanBarCodeData.BarCode)] = scanBarCodeRecord.BarCode;
            dr[nameof(ScanBarCodeData.GroupCode)] = scanBarCodeRecord.GroupCode;
            dr[nameof(ScanBarCodeData.Sort)] = barCodeCount;
            dr[nameof(ScanBarCodeData.CreateDateTime)] = scanBarCodeRecord.CreateDateTime;
            dataTable.Rows.InsertAt(dr, 0);
        }


        /// <summary>
        /// 清空表格
        /// </summary>
        /// <param name="scanBarCodeRecord"></param>
        private void ClearGrid()
        {
            this.groupCode = string.Empty;
            if (dataTable.Rows.Count > 100 && dataTable.Rows.Count % groupCount == 0)
            {
                dataTable.Rows.Clear();
            }
        }


        /// <summary>
        /// 创建扫描对象
        /// </summary>
        /// <param name="barCodes"></param>
        /// <returns></returns>
        private ScanBarCodeRecord CreateScanBarCodeRecord(string barCode)
        {

            ScanBarCodeRecord scanBarCodeRecord = new ScanBarCodeRecord()
            {
                BarCode = barCode,
                CreateDateTime = DateTime.Now,
                CreateUserId = UserSession.UserId,
                CreateUserName = UserSession.UserName,
                GroupCode = groupCode,
                Remark = string.Empty,
                Sort = 0
            };
            scanBarCodeRecord.Sort = scanBarCodeRecords.Count + 1;
            return scanBarCodeRecord;
        }



        /// <summary>
        /// 显示消息
        /// </summary>
        /// <param name="message"></param>
        /// <param name="scanResult"></param>
        /// <param name="addNewLine"></param>
        private void ShowMessage(string message, ScanResult scanResult = ScanResult.Pass, bool addNewLine = true)
        {
            if (txtMessage.TextLength > 100)
            {
                txtMessage.Clear();
            }
            //字体
            txtMessage.SelectionFont = new Font("微软雅黑", 15, FontStyle.Regular, GraphicsUnit.Pixel, 134);
            message = $"{DateTime.Now.ToString("HH:mm:ss")}->{message}";
            Color color = Color.Green;
            if (scanResult != ScanResult.Pass)
            {
                color = Color.Red;
            }

            if (addNewLine)
            {
                message += Environment.NewLine;
            }
            txtMessage.SelectionStart = txtMessage.TextLength;
            txtMessage.SelectionLength = 0;
            txtMessage.SelectionColor = color;
            txtMessage.AppendText(message);
            txtMessage.SelectionColor = txtMessage.ForeColor;
            txtMessage.ScrollToCaret();
        }

        /// <summary>
        /// 打印
        /// </summary>
        private void Print(Dictionary<string, string> paramaters)
        {
            if (!File.Exists(templateFile))
            {
                throw new FileNotFoundException($"文件模板{templateFile}不存在");
            }
            gridReport.TemplateFile = templateFile;
            gridReport.Print(paramaters);
        }
    }
}
